﻿namespace System.Linq
{
	using System;
	using System.Collections.Generic;

	/// <summary>
	/// Contains a set of extension methods for dictionaries.
	/// </summary>
	public static class DictionaryExtensions
	{
		/// <summary>
		/// Swaps keys and values in a given dictionary.
		/// </summary>
		/// <typeparam name="TKey"></typeparam>
		/// <typeparam name="TValue"></typeparam>
		/// <param name="source"></param>
		/// <returns>Returns a new dictionary, in which keys and values are swapped.</returns>
		public static IDictionary<TValue, TKey> Swap<TKey, TValue>(this IDictionary<TKey, TValue> source)
		{
			if (source == null)
				throw new ArgumentNullException("source");

			return source.ToDictionary(kv => kv.Value, kv => kv.Key);
		}

		/// <summary>
		/// Finds the key for a specified value.
		/// </summary>
		/// <typeparam name="TKey"></typeparam>
		/// <typeparam name="TValue"></typeparam>
		/// <param name="source"></param>
		/// <param name="value">The value to search.</param>
		/// <returns>Returns the key of the found entry.</returns>
		public static TKey FindKey<TKey, TValue>(this IDictionary<TKey, TValue> source, TValue value) where TValue : IEquatable<TValue>
		{
			if (source == null)
				throw new ArgumentNullException("source");

			KeyValuePair<TKey, TValue> pair = source.SingleOrDefault(kvp => kvp.Value.Equals(value));

			return pair.Key;
		}
	}
}
